

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:myapp/utils/sp_utils.dart';

import '../../constants.dart';

class CookieInterceptor extends Interceptor{

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    //取出本地cookie
    SpUtils.getStringList(Constants.SP_COOKIE_LIST).then((cookieList){
      //放到请求头中
      options.headers[HttpHeaders.cookieHeader] = cookieList;
      //继续往下执行
      handler.next(options);
    });
    
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    //登录接口
    if(response.requestOptions.path.contains("user/login")){
      print("CookieInterceptor: 响应头: ${response.headers}"); // 打印所有响应头，帮助调试
      //取出cookie信息
      // dynamic list =  response.headers[HttpHeaders.setCookieHeader];
      // 使用不区分大小写的方式获取
      List<String>? list = response.headers[HttpHeaders.setCookieHeader.toLowerCase()];

      if(list != null && list.isNotEmpty){
        List<String> cookieList = [];
        for (String cookie in list) {
          cookieList.add(cookie);
          print("CookieInterceptor cookie =${cookie.toString()}");
        }
        SpUtils.saveList(Constants.SP_COOKIE_LIST, cookieList);
      }else{
        print("CookieInterceptor: 登录接口未返回Set-Cookie头");
      }
    }
    super.onResponse(response, handler);
  }
}